﻿/// <reference path="../jquery-1.7.1.js"/>
/// <reference path="../jquery.cookie.js"/>


$(function () {
    var cookieOptions = {
        path: "/",
        expires: 3600
    };
    // ---- annotations
    var container = $("#annotation-container");
    var mainDiv = $("#main");

    var loadedAnnotations = [];

    function displayAnnotation() {
        container.find(".annotation").remove();
        container.height(1); //reset height
        container.height(mainDiv.outerHeight(false));

        loadedAnnotations.sort(function (a, b) {
            // higher rating comes first, if two ratings are the same then new item comes first
            if (a.Rating != b.Rating) {
                return b.Rating - a.Rating;
            }
            return b.Id - a.Id;
        });

        var placeholder = $('<div class="annotation"><span>abc测试</span></div>');
        placeholder.appendTo(container);
        var slotHeight = placeholder.outerHeight(true);
        placeholder.remove();

        var containerWidth = container.width();
        var containerHeight = container.height();

        var freeSlotRecords = [];

        $.each(loadedAnnotations, function (i, item) {
            var elem = $('<div class="annotation"><span></span></div>');
            elem.find("span").text(item.AnnotationContent).attr("title", item.AnnotationContent).end();
            elem.css("visibility", "hidden")
                .appendTo(container);

            var elemWidth = elem.outerWidth(true);
            var elemHeight = elem.outerHeight(true);

            var preferredSlot = Math.round((item.Position * containerHeight) / slotHeight) * slotHeight;

            var targetLeft;
            var targetTop = null;

            function scanSlot(slot) {
                var foundSlot = false;
                // we may support multi-line in the future
                if (!freeSlotRecords[slot]) {
                    // this slot doesn't have any annotation
                    targetLeft = 0;
                    targetTop = slot;
                    freeSlotRecords[slot] = [];
                    var remainingWidth = containerWidth - elemWidth;
                    if (remainingWidth > 0) {
                        freeSlotRecords[slot].push({
                            start: elemWidth,
                            width: remainingWidth
                        });
                    }
                    foundSlot = true;
                } else {
                    $.each(freeSlotRecords[slot], function (i, value) {
                        if (value.width < elemWidth) {
                            return; // continue
                        }
                        foundSlot = true;
                        targetLeft = value.start;
                        targetTop = slot;
                        if (value.width > elemWidth) {
                            value.start += elemWidth;
                            value.width -= elemWidth;
                        } else {
                            freeSlotRecords[slot].splice(i, 1);
                        }
                        return false; // break
                    });
                }
                return foundSlot;
            };

            for (var i = 0; i < 10; i++) {
                var pos = preferredSlot + i * slotHeight;
                if (pos < containerHeight && scanSlot(pos)) {
                    break;
                }
                pos = preferredSlot - i * slotHeight;
                if (i > 0 && pos >= 0 && scanSlot(pos)) {
                    break;
                }
            }

            if (targetTop === null) {
                // we can't find a appropriate place for this annotation
                elem.remove();
                return;
            }

            elem.css({
                "left": targetLeft + "px",
                "top": targetTop + "px",
                "visibility": "visible"
            });
        });
        $("#annotation-loading").hide();
    }

    function loadAnnotations() {
        $.getJSON(annotationListUrl,
                  {},
                  function (data, textStatus) {
                      loadedAnnotations = loadedAnnotations.concat(data);
                      displayAnnotation();
                  });
    };


    mainDiv.resize(function () {
        displayAnnotation();
    });

    $(window).resize(function () {
        displayAnnotation();
    });

    var clickPosition = 0.0;
    var isPosting = false;
    container.click(function (e) {
        if (isPosting) {
            return;
        }
        clickPosition = (e.pageY - container.offset().top) / container.height();
        $("#annotation-post-input").val("");
        $("#annotation-post").css("top", (clickPosition * 100) + "%")
                             .find(".annotation-post-error, .annotation-post-no-content").hide().end()
                             .show();
        $("#annotation-post-input").focus();
    });
    $("#annotation-post").attr("unselectable", "on")
                         .attr("onselectstart", "return false;");
    $("#annotation-post-cancel").click(function () {
        $("#annotation-post").hide();
    });
    $("#annotation-post-input").keydown(function (e) {
        if (e.which == 13) { // enter key
            $("#annotation-post-submit").click();
        } else if (e.which == 27) { // esc key
            $("#annotation-post-cancel").click();
        };
        e.stopPropagation(); // disable document hotkey
    });
    $("#annotation-post-submit").click(function () {
        if (isPosting) {
            return;
        }
        var postBox = $("#annotation-post");
        postBox.find(".annotation-post-error, .annotation-post-no-content").hide();
        var content = $("#annotation-post-input").val();
        if (!content) {
            $(".annotation-post-no-content").show();
            return;
        }
        $("#annotation-post-input").blur();
        postBox.find(".annotation-post-sending").show();
        var postButton = $(this);
        postButton.attr("disabled", "disabled");
        isPosting = true;
        $.ajax({
            type: 'POST',
            url: annotationAddUrl,
            data: {
                ChapterId: chapterId,
                Position: clickPosition,
                Content: content
            },
            complete: function () {
                postButton.attr("disabled", null);
                postBox.find(".annotation-post-sending").hide();
                isPosting = false;
            },
            success: function (newId) {
                postBox.hide();
                loadedAnnotations.splice(0, 0, {
                    "Id": parseInt(newId),
                    "AnnotationContent": content,
                    "Position": clickPosition,
                    "Rating": 0
                });
                displayAnnotation();
            },
            error: function () {
                postBox.find(".annotation-post-error").show();
            }
        });
    });
    $("#annotation-post").click(function (e) {
        e.stopPropagation();
        return false;
    });

    // ---- user customizations
    function setFontSize(sourceElem) {
        var className = $(sourceElem).data("originalClass");
        var sizeString = /font-size-((\d|-)+)/.exec(className)[1];
        if (sizeString) {
            var size = parseFloat(sizeString.replace("-", "."));
            if (!isNaN(size) && size > 0) {
                $("#content-wrap").css("font-size", size + "em");
                $(".font-size-select span").removeClass("selected-font-size");
                $(sourceElem).addClass("selected-font-size");
                $.cookie("readPageFontSize", className, cookieOptions);
            }
        }
    }
    function restoreFontSize() {
        var storedFontSizeElem = $.cookie("readPageFontSize");
        if (storedFontSizeElem) {
            var elem = $("." + storedFontSizeElem);
            if (elem.size() > 0) {
                setFontSize(elem);
            }
        }
    }
    function setBackColor(color) {
        $(".chapter-content").css("background-color", color);
        $.cookie("readPageBackColor", color, cookieOptions);
    }
    function restoreBackColor() {
        var storedColor = $.cookie("readPageBackColor");
        if (storedColor) {
            setBackColor(storedColor);
        }
    }
    $(".font-size-select span").each(function () {
        $(this).data("originalClass", $(this).attr("class"))
               .click(function () {
                   setFontSize(this);
                   displayAnnotation();
               });
    });

    $(".back-color-select span").each(function () {
        $(this).css("background-color", $(this).attr("class"))
               .click(function () {
                   setBackColor($(this).css("background-color"));
               });
    });

    // ----- auto-scrolling
    var autoScrollEnabled = false;
    var autoScrollInterval = 100;
    function doAutoScroll() {
        if (!autoScrollEnabled) {
            return;
        }
        window.scrollBy(0, 5);
        setTimeout(doAutoScroll, autoScrollInterval);
    }

    $("#content-wrap").dblclick(function (e) {
        if (window.getSelection) {
            window.getSelection().removeAllRanges();
        }
        else if (document.selection) { // should come last; Opera!
            document.selection.empty();
        }
        autoScrollEnabled = true;
        doAutoScroll();
        e.preventDefault();
        return false;
    });

    $(document).mousedown(function () {
        autoScrollEnabled = false;
    });

    $(document).keydown(function (e) {
        if (autoScrollEnabled) {
            if (e.which == 38 || e.which == 40) { // UP and DOWN
                autoScrollInterval += (e.which - 39) * 10;
                autoScrollInterval = Math.max(Math.min(autoScrollInterval, 300), 10);
                e.preventDefault();
                return false;
            }
        }
    });

    // ----- navigation hotkey

    $(document).keydown(function (e) {
        var link;
        if (e.which == 37) { // LEFT
            link = $("#link-prev-page").attr("href");
        } else if (e.which == 39) { // RIGHT
            link = $("#link-next-page").attr("href");
        }
        if (link) {
            location.href = link;
        }
    });

    // ----- toggle sidebar button

    $("#toggle-sidebar-button").click(function () {
        var body = $("body");
        body.toggleClass("hide-sidebar");
        $.cookie("sidebarHidden", body.hasClass("hide-sidebar") ? "1" : "0", cookieOptions);
    }).mouseenter(function () {
        $(this).addClass("hover", "fast");
    }).mouseleave(function () {
        $(this).removeClass("hover", "fast");
    });

    restoreSidebarHidden = function () {
        if ($.cookie("sidebarHidden") === "1") {
            $("body").addClass("hide-sidebar");
        }
    };

    // ----- initialization
    restoreFontSize();
    restoreBackColor();
    restoreSidebarHidden();
    loadAnnotations();

});

